<?php

namespace app\guild\controller;

use app\common\model\GuildManagerModel;
use app\common\model\LiveCategoryTopModel;
use app\common\model\LiveHistoryModel;
use app\common\model\LiveModel;
use app\common\model\LiveCategoryModel;
use app\common\model\UserModel;
use app\common\model\AnchorFansModel;
use app\common\model\RegSourceModel;
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
use think\Db;
use think\facade\Request;
use think\facade\Cache;
use app\common\model\GiftLogModel;

class ReportController extends BaseController
{

    public function chat()
    {
        // 分类
        $category = LiveCategoryModel::all();
        $this->assign("category", $category);

        $this->timeSet();
        return $this->fetch();
    }

    public function anchor()
    {
        return $this->fetch();
    }


    public function chatModel($isPage = true, $page = 0, $categoryid, $limit = 0, $nickName = 0, $orderNo = 0, $payStatus = 0, $startTime = 0, $endTime = 0)
    {
        $model = LiveHistoryModel::alias('LS')
            ->leftJoin(config('database.database') . '.db_user user', 'LS.anchorid = user.id')
            ->field('LS.id ,LS.anchorid ,LS.liveid ,LS.title ,LS.stream ,LS.pull_url ,LS.categoryid ,LS.orientation ,LS.start_stamp ,LS.end_stamp ,LS.gift_profit ,LS.barrage_human_count ,LS.barrage_time_count ,LS.active_viewer ,LS.viewer_count ,LS.high_count ,LS.avg_line ,LS.high_hot ,LS.avg_hot ,LS.new_face,LS.hot, LS.event_title as event_title, LS.gift_num, LS.anchor_income as anchor_income, user.nick_name,user.sharing_ratio')
            ->order(['hot' => 'desc']);


        if ($categoryid > 0) {
            $model->where("categoryid", $categoryid);
        }

        // 管理的用户id
        $manage_uid = parent::getGuildUserId();
        $model->whereIn("anchorid", $manage_uid);

        // if ($nickName) {
        //     $model->whereLike('nick_name', '%' . trim($nickName) . '%');
        // }
        // if ($orderNo) {
        //     $model->where('order_no', '=', $orderNo);
        // }
        // if ($payStatus) {
        //     $model->where('pay_status', '=', $payStatus);
        // }
        if ($startTime) {
            $model->where('end_stamp', '>=', strtotime($startTime));
        }
        if ($endTime) {
            $model->where('end_stamp', '<=', strtotime($endTime));
        }
        if ($isPage) {
            $model->limit(($page - 1) * $limit, $limit);
        } else {
            $model->limit(100);
        }

        $data = $model->select();
        if (count($data)) {
            return $this->live_date2struct($data, 2);
        }
        return [];
    }

    public function anchorModel($isPage = true, $page = 0, $limit = 0, $nickName = 0, $liveid = 0, $guild = 0, $level = 0, $startTime = 0, $endTime = 0)
    {

        $model = LiveHistoryModel::alias('LS')
            ->leftJoin(config('database.database') . '.db_user user', 'LS.anchorid = user.id')
            ->field('LS.id ,LS.anchorid ,LS.liveid ,LS.title ,LS.stream ,LS.pull_url ,LS.categoryid ,LS.orientation ,LS.start_stamp ,LS.end_stamp ,LS.gift_profit ,LS.barrage_human_count ,LS.barrage_time_count ,LS.active_viewer ,LS.viewer_count ,LS.high_count ,LS.avg_line ,LS.high_hot ,LS.avg_hot ,LS.new_face,user.nick_name,user.sharing_ratio')
            ->order(['start_stamp' => 'desc'])->group("LS.anchorid");

        $countModel = LiveHistoryModel::alias('LS')
            ->leftJoin(config('database.database') . '.db_user user', 'LS.anchorid = user.id')
            ->field('LS.id ,LS.anchorid ,LS.liveid ,LS.title ,LS.stream ,LS.pull_url ,LS.categoryid ,LS.orientation ,LS.start_stamp ,LS.end_stamp ,LS.gift_profit ,LS.barrage_human_count ,LS.barrage_time_count ,LS.active_viewer ,LS.viewer_count ,LS.high_count ,LS.avg_line ,LS.high_hot ,LS.avg_hot ,LS.new_face,user.nick_name,user.sharing_ratio')
            ->order(['start_stamp' => 'desc'])->group("LS.anchorid");

        // 管理的用户id
        $manage_uid = parent::getGuildUserId();
        $model->whereIn("anchorid", $manage_uid);
        $countModel->whereIn("anchorid", $manage_uid);

        if ($nickName) {
            $model->whereLike('nick_name', '%' . trim($nickName) . '%');
            $countModel->whereLike('nick_name', '%' . trim($nickName) . '%');
        }
        if ($liveid) {
            $model->where("anchorid", $liveid);
            $countModel->where("anchorid", $liveid);
        }
        if ($startTime) {
            $model->where('start_stamp', '>=', strtotime($startTime));
            $countModel->where('start_stamp', '>=', strtotime($startTime));
        }
        if ($endTime) {
            $model->where('end_stamp', '<=', strtotime($endTime));
            $countModel->where('end_stamp', '<=', strtotime($endTime));
        }
        $count = $countModel->count();

        if ($isPage) {
            $model->limit(($page - 1) * $limit, $limit);
        } else {
            if ($limit < 20) {
                $limit = 20;
            }
            $model->limit($limit);
        }
        $data = $model->select();

        foreach ($data as $key => $value) {
            // 场次
            $timesQuery = LiveHistoryModel::where("anchorid", $value['anchorid']);
            if ($startTime) {
                $timesQuery->where("start_stamp", ">=", strtotime($startTime));
            }
            if ($endTime) {
                $timesQuery->where('end_stamp', '<=', strtotime($endTime));
            }
            $data[$key]['times'] = $timesQuery->count();
            $data[$key]['times'] = $data[$key]['times'] > 0 ? $data[$key]['times'] : 1;

            $query = LiveHistoryModel::field("sum(end_stamp - start_stamp) as `long`, sum(gift_num) as gift_num, sum(gift_profit) as gift_profit, sum(anchor_income) as anchor_income, sum(barrage_time_count) as barrage_time_count, sum(new_fans_count) as new_fans_count")->where("anchorid", $value['anchorid']);

            if ($startTime) {
                $query->where("start_stamp", ">=", strtotime($startTime));
            }
            if ($endTime) {
                $query->where('end_stamp', '<=', strtotime($endTime));
            }

            $his = $query->find();

            // 总时长 - 分钟
            $data[$key]['duration'] = intval($his['long'] / 60);
            // 平均时长
            $data[$key]['avg_duration'] = intval($data[$key]['duration'] / $data[$key]['times']);
            // 送礼总人数
            $giftQuery = GiftLogModel::where("anchorid", $value['anchorid'])->group("uid");
            if ($startTime) {
                $giftQuery->where("create_time", ">=", $startTime);
            }
            if ($endTime) {
                $giftQuery->where('create_time', '<=', $endTime);
            }

            $data[$key]['gift_num_people'] = $giftQuery->count();
            // 平均送礼人数
            $data[$key]['avg_gift_num_people'] = sprintf("%0.1f", $data[$key]['gift_num_people'] / $data[$key]['times']);
            // 礼物总价值
            $data[$key]['gift_profit'] = intval($his['gift_profit']);
            // 平均送礼价值
            $data[$key]['avg_gift_profit'] = intval($his['gift_profit'] / $data[$key]['times']);
            // 主播收益
            $data[$key]['anchor_income'] = intval($his['anchor_income']);
            // 平均主播收益
            $data[$key]['avg_anchor_income'] = intval($his['anchor_income'] / $data[$key]['times']);
            // 弹幕总数
            $data[$key]['barrage_time_count'] = $his['barrage_time_count'];
            // 平均弹幕数量
            $data[$key]['avg_barrage_time_count'] = intval($his['barrage_time_count'] / $data[$key]['times']);
            // 平均新增粉丝
            $data[$key]['avg_new_fans_count'] = intval($his['new_fans_count'] / $data[$key]['times']);
            // 总粉丝数
            $data[$key]['fans_count'] = AnchorFansModel::where("anchorid", $value['anchorid'])->count();
        }
        if (count($data)) {
            return [$data, $count];
        }

        return [[], 0];
    }

    /**
     * 直播中
     * @param $page
     * @param $limit
     * @param $categoryid
     */
    public function get_on_live($page, $limit, $categoryid)
    {
        $where = ['status' => 1];
        if ($categoryid > 0) {
            $where['categoryid'] = $categoryid;
        }

        // 管理的用户id
        $manage_uid = parent::getGuildUserId();

        // 直播数据
        $on_live = LiveModel::where($where)
            ->with(['user' => function ($query) {
                $query->field('nick_name, id');
            }])
            ->whereIn("anchorid", $manage_uid)
            ->order(['hot' => 'desc'])
            ->limit(($page - 1) * $limit, $limit)
            ->select()->toArray();

        if (empty($on_live)) {
            return array();
        }

        // 默认统计数据
        $default_cache_statis = [
            'active_viewer'       => 0,
            'anchorid'            => 0,
            'avg_hot'             => 0,
            'avg_line'            => 0,
            'barrage_human_count' => 0,
            'barrage_time_count'  => 0,
            'high_count'          => 0,
            'high_hot'            => 0,
            'hot'                 => 0,
            'liveid'              => 0,
            'viewer_count'        => 0,
            'attenuation_num'     => 0,
            'text_message'        => 0,
            'gift_total_num'      => 0,
            'gift_total_price'    => 0,
            'gift_total_diamond_num'   => 0,
            'gift_total_diamond_price' => 0,
        ];

        $cache_redis = Cache::store('redis');

        foreach ($on_live as &$value) {
            // 主播统计信息
            $anchor_cache_statis = $cache_redis->hGetAll("statisticsGroup_" . $value['anchorid']);
            $value['live']       = !empty($anchor_cache_statis) ? $anchor_cache_statis : $default_cache_statis;
            unset($anchor_cache_statis);
        }
        unset($cache_redis, $default_cache_statis);

        return $this->live_date2struct($on_live, 1);
    }

    // status 1 直播中， 2 历史数据
    private function live_date2struct($data = [], $status)
    {
        $data = is_object($data) ? $data->toArray() : $data;
        if (empty($data)) {
            return array();
        }

        // 分类列表 新粉丝总计 粉丝总计
        $category_list = $new_fans_count = $fans_count = [];
        $top_category  = LiveCategoryTopModel::select()->toArray();
        $top_category  = array_column($top_category, null, 'id');

        // 分类查询
        $categryid_arr = array_column($data, 'categoryid');
        $categryid_arr = array_filter(array_unique($categryid_arr));

        // 直播间id
        $liveid_arr = array_column($data, 'liveid');
        $liveid_arr = array_filter(array_unique($liveid_arr));

        // 主播id数组
        $anchorid_arr = array_column($data, 'anchorid');
        $anchorid_arr = array_filter(array_unique($anchorid_arr));

        if ($categryid_arr) {
            $category_list = LiveCategoryModel::whereIn('id', $categryid_arr)->field('id,title')->select()->toArray();
            $category_list = array_column($category_list, null, 'id');
        }

        if ($anchorid_arr) {
            // 粉丝总数
            $fans_count = AnchorFansModel::field('anchorid,count(*) as count')
                ->whereIn("anchorid", $anchorid_arr)->group('anchorid')->select()->toArray();
            $fans_count = array_column($fans_count, 'count', 'anchorid');

            // 新粉丝数  历史数据的时候需要新粉丝数
            if ($liveid_arr && $status == 1) {
                $new_fans_count = AnchorFansModel::field('anchorid,count(*) as count')->whereIn('live_id', $liveid_arr)
                    ->whereIn("anchorid", $anchorid_arr)->group('anchorid')->select()->toArray();
                $new_fans_count = array_column($new_fans_count, 'count', 'anchorid');
            }
        }
        $pack = [];
        if ($status == 1) {
            foreach ($data as $key => $value) {
                $pack[$key]['uid']                 = $value['anchorid'];
                $pack[$key]['nick_name']           = isset($value['user']['nick_name']) ? $value['user']['nick_name'] : '';
                $pack[$key]['live_id']             = $value['liveid'];
                $pack[$key]['title']               = $value['title'];
                $pack[$key]['category']            = $value['category'];
                $pack[$key]['category_text']       = isset($top_category[$value['category']]) ? $top_category[$value['category']]['title'] : '';
                $pack[$key]['event_title']         = $value['event_title'];
                $pack[$key]['hot']                 = $value['hot'];
                $pack[$key]['new_fans_count']      = isset($new_fans_count[$value['anchorid']]) ? $new_fans_count[$value['anchorid']] : 0;
                $pack[$key]['fans_count']          = isset($fans_count[$value['anchorid']]) ? $fans_count[$value['anchorid']] : 0;
                $pack[$key]['message_count']       = isset($value['live']['text_message']) ? $value['live']['text_message'] : 0;
                $pack[$key]['status']              = 1;  // 状态直播中
                $pack[$key]['viewer_count']        = isset($value['live']['viewer_count']) ? $value['live']['viewer_count'] : 0;
                $pack[$key]['online_peak']         = isset($value['live']['barrage_time_count']) ? $value['live']['barrage_time_count'] : 0;
                $pack[$key]['gift_num']            = isset($value['live']['gift_total_num']) ? $value['live']['gift_total_num'] : 0;
                $pack[$key]['gift_total_value']    = isset($value['live']['gift_total_price']) ? $value['live']['gift_total_price'] : 0;
                // 鹰钻
                $pack[$key]['gift_diamond_total_num']   = isset($value['live']['gift_diamond_total_num']) ? $value['live']['gift_diamond_total_num'] : 0;
                $pack[$key]['gift_diamond_total_price'] = isset($value['live']['gift_diamond_total_price']) ? bcdiv(strval($value['live']['gift_diamond_total_price']), '100', 2) : 0;
                $pack[$key]['anthor_total_income'] = $value['profit'];
            }
        }

        if ($status == 2) {
            foreach ($data as $key => $value) {
                $pack[$key]['uid']                 = $value['anchorid'];
                $pack[$key]['nick_name']           = $value['nick_name'];
                $pack[$key]['live_id']             = $value['liveid'];
                $pack[$key]['title']               = $value['title'];
                $pack[$key]['category']            = $value['categoryid'];
                $pack[$key]['category_text']       = isset($category_list[$value['categoryid']]) ? $category_list[$value['categoryid']]['title'] : '';
                $pack[$key]['event_title']         = $value['event_title'];
                $pack[$key]['hot']                 = $value['hot'];
                $pack[$key]['fans_count']          = isset($fans_count[$value['anchorid']]) ? $fans_count[$value['anchorid']] : 0;
                $pack[$key]['new_fans_count']      = $value['new_face'];
                $pack[$key]['message_count']       = $value['barrage_time_count'];
                $pack[$key]['status']              = 2;  // 历史数据
                $pack[$key]['viewer_count']        = $value['viewer_count'];
                $pack[$key]['online_peak']         = $value['high_count'];
                $pack[$key]['gift_num']            = $value['gift_num'];
                $pack[$key]['gift_total_value']    = $value['gift_profit'];
                // 鹰钻
                $pack[$key]['gift_diamond_total_num']   = $value['gift_diamond_total_num'];
                $pack[$key]['gift_diamond_total_price'] = bcdiv(strval($value['gift_diamond_total_price']), '100', 2);
                $pack[$key]['anthor_total_income'] = $value['anchor_income'];
            }
        }

        return $pack;
    }

    public function get_chat()
    {

        $status = Request::param("status", 1);      // 1直播中, 2历史数据

        $categoryid = Request::param("categoryid", 0);

        $page  = Request::param("page");
        $limit = Request::param("limit");

        $nickName  = Request::param("nick_name", 0);
        $guild     = Request::param("guild", 0);
        $level     = Request::param("level", 0);
        $startTime = Request::param("start_time", 0);
        $endTime   = Request::param("end_time", 0);

        // 注意分组
        if ($status == 1) {
            $get_on_live = $this->get_on_live($page, $limit, $categoryid);
            if (count($get_on_live)) {
                $count_live_where = [];
                if ($categoryid > 0) {
                    $count_live_where[] = ['categoryid', '=', $categoryid];
                }
                // 管理的用户id
                $manage_uid         = parent::getGuildUserId();
                $count_live_where[] = ['anchorid', 'in', $manage_uid];

                return json([
                    "code"  => 0,
                    "msg"   => "",
                    "data"  => $get_on_live,
                    "count" => LiveModel::where($count_live_where)->count(),
                ]);
            }
            return self::bulidFail("未查询到相关数据");
        }

        if ($status == 2) {
            $data = $this->chatModel(true, $page, $categoryid, $limit, $nickName, $guild, $level, $startTime, $endTime);
            if (count($data) > 0) {
                $query = LiveHistoryModel::field("*");

                // 管理的用户id
                $manage_uid = parent::getGuildUserId();
                $query->whereIn("anchorid", $manage_uid);

                if ($categoryid > 0) {
                    $query->where("categoryid", $categoryid);
                }
                if ($startTime) {
                    $query->where('start_stamp', '>=', strtotime($startTime));
                }
                if ($endTime) {
                    $query->where('end_stamp', '<=', strtotime($endTime));
                }
                $count = $query->count();
                if (count($data) > 0) {
                    return json([
                        "code"  => 0,
                        "msg"   => "",
                        "data"  => $data,
                        "count" => $count
                    ]);
                }
            }
            return self::bulidFail("未查询到相关数据");
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function get_summary()
    {
        $status = Request::param("status", 1);      // 1直播中, 2历史数据

        $categoryid = Request::param("categoryid", 0);
        $page       = Request::param("page");
        $limit      = Request::param("limit");

        $nickName  = Request::param("nick_name", 0);
        $guild     = Request::param("guild", 0);
        $level     = Request::param("level", 0);
        $startTime = Request::param("start_time", 0);
        $endTime   = Request::param("end_time", 0);

        $summary = [
            'new_fans'         => 0,
            'live_count'       => 0,
            'message_count'    => 0,
            'viewer_count'     => 0,
            'online_peak'      => 0,
            'hot'              => 0,
            'gift_num'         => 0,
            'gift_total_value' => 0,
            'anchor_income'    => 0
        ];

        // 管理的用户id
        $manage_uid = parent::getGuildUserId();

        // 1直播中, 2历史数据
        if ($status == 1) {
            $on_where = [
                ['anchorid', 'in', $manage_uid],
                ['status', '=', 1],
            ];
            if ($categoryid > 0) {
                $on_where[] = ['categoryid', '=', $categoryid];
            }
            $onLive = LiveModel::where($on_where)->select();

            foreach ($onLive as $value) {
                if (!in_array($value['anchorid'], $manage_uid)) {
                    continue;
                }
                // 直播场次
                $summary['live_count']++;

                $cache_anchor_statis = Cache::store('redis')->hGetAll("statisticsGroup_" . $value['anchorid']);

                $default_data = [
                    'active_viewer'       => 0,
                    'anchorid'            => 0,
                    'avg_hot'             => 0,
                    'avg_line'            => 0,
                    'barrage_human_count' => 0,
                    'barrage_time_count'  => 0,
                    'high_count'          => 0,
                    'high_hot'            => 0,
                    'hot'                 => 0,
                    'gift_total_price'    => 0,
                    'liveid'              => 0,
                    'viewer_count'        => 0,
                    'attenuation_num'     => 0,
                    'text_message'        => 0,
                    'gift_total_num'      => 0,
                ];

                $live = !empty($cache_anchor_statis) ? $cache_anchor_statis : $default_data;

                $summary['new_fans']         += AnchorFansModel::where(["live_id" => $value['liveid'], "anchorid" => $value['anchorid']])->count();
                $summary['message_count']    += isset($live['text_message']) ? $live['text_message'] : 0;
                $summary['viewer_count']     += isset($live['viewer_count']) ? $live['viewer_count'] : 0;
                $summary['online_peak']      += isset($live['barrage_time_count']) ? $live['barrage_time_count'] : 0;
                $summary['hot']              += isset($live['hot']) ? $live['hot'] : 0;
                $summary['gift_num']         += isset($live['gift_total_num']) ? $live['gift_total_num'] : 0;
                $summary['gift_total_value'] += isset($live['gift_total_price']) ? $live['gift_total_price'] : 0;
                $summary['anchor_income']    += LiveModel::where(["anchorid" => $value['anchorid']])->Find()['profit'];
            }
        }

        if ($status == 2) {
            $query = LiveHistoryModel::field("*");
            $query->whereIn('anchorid', $manage_uid);

            if ($categoryid > 0) {
                $query->where('categoryid', $categoryid);
            }
            if ($startTime) {
                $query->where('end_stamp', '>=', strtotime($startTime));
            }
            if ($endTime) {
                $query->where('end_stamp', '<=', strtotime($endTime));
            }
            $summary['live_count'] = $query->count();

            // TODO 加粉记录直播分类
            $query = LiveHistoryModel::field("sum(new_face) as new_face, sum(barrage_time_count) as barrage_time_count, sum(viewer_count) as viewer_count, sum(high_count) as high_count, sum(hot) as hot, sum(gift_num) as gift_num, sum(gift_profit) as gift_profit, sum(anchor_income) as anchor_income");
            $query->whereIn('anchorid', $manage_uid);

            if ($categoryid > 0) {
                $query->where('categoryid', $categoryid);
            }
            if ($startTime) {
                $query->where('end_stamp', '>=', strtotime($startTime));
            }
            if ($endTime) {
                $query->where('end_stamp', '<=', strtotime($endTime));
            }
            $res                         = $query->find()->toArray();
            $summary['new_fans']         += $res['new_face'];
            $summary['message_count']    += $res['barrage_time_count'];
            $summary['viewer_count']     += $res['viewer_count'];
            $summary['online_peak']      += $res['high_count'];
            $summary['hot']              += $res['hot'];
            $summary['gift_num']         += $res['gift_num'];
            $summary['gift_total_value'] += $res['gift_profit'];
            $summary['anchor_income']    += $res['anchor_income'];
        }

        return self::bulidSuccess([0 => $summary]);
    }

    public function export_chat()
    {
        $status = Request::param("status", 1);      // 1直播中, 2历史数据

        $categoryid = Request::param("categoryid", 0);
        $page       = intval(Request::param("page", 0));
        $limit      = intval(Request::param("limit", 0));
        $nickName   = Request::param("nick_name", 0);
        $guild      = Request::param("guild", 0);
        $level      = Request::param("level", 0);
        $startTime  = Request::param("start_time", 0);
        $endTime    = Request::param("end_time", 0);

        $data = [];
        if ($status == 1) {
            $data = $this->get_on_live($page, $limit, $categoryid);
        }
        if ($status == 2) {
            $data = $this->chatModel(true, 1, $categoryid, 100, $nickName, $guild, $level, $startTime, $endTime);
        }

        if (empty($data)) {
            return $this->error('未查询到相关数据');
        }

        $writer = WriterEntityFactory::createXLSXWriter();
        $file   = "{$_SERVER['DOCUMENT_ROOT']}/uploads/" . time() . rand(10000, 99999) . 'xlsx';
        $writer->openToFile($file);
        $header    = [
            WriterEntityFactory::createCell('主播ID'),
            WriterEntityFactory::createCell('主播昵称'),
            WriterEntityFactory::createCell('直播间编号'),
            WriterEntityFactory::createCell('直播间标题'),
            WriterEntityFactory::createCell('直播类别'),
            WriterEntityFactory::createCell('热度值'),
            WriterEntityFactory::createCell('新增粉丝数'),
            WriterEntityFactory::createCell('总粉丝数'),
            WriterEntityFactory::createCell('新增消息数'),
            WriterEntityFactory::createCell('观看人次'),
            WriterEntityFactory::createCell('人数峰值'),
            WriterEntityFactory::createCell('礼物总数/宝石'),
            WriterEntityFactory::createCell('主播收益'),
        ];
        $singleRow = WriterEntityFactory::createRow($header);
        $writer->addRow($singleRow);

        $multipleRows = [];
        foreach ($data as $v) {
            $cells          = [
                WriterEntityFactory::createCell($v['uid']),
                WriterEntityFactory::createCell($v['nick_name']),
                WriterEntityFactory::createCell((string)$v['live_id']),
                WriterEntityFactory::createCell($v['title']),
                WriterEntityFactory::createCell($v['category_text'] . "/" . $v['event_title']),
                WriterEntityFactory::createCell($v['hot']),
                WriterEntityFactory::createCell($v['new_fans_count']),
                WriterEntityFactory::createCell($v['fans_count']),
                WriterEntityFactory::createCell($v['message_count']),
                WriterEntityFactory::createCell($v['viewer_count']),
                WriterEntityFactory::createCell($v['online_peak']),
                WriterEntityFactory::createCell($v['gift_num'] . "/" . $v['gift_total_value']),
                WriterEntityFactory::createCell($v['anthor_total_income']),
            ];
            $multipleRows[] = WriterEntityFactory::createRow($cells);
        }

        $writer->addRows($multipleRows);

        $writer->close();

        return download($file, '直播报表.xlsx');
    }

    public function get_anchor()
    {
        $page      = Request::param("page");
        $nickName  = Request::param("nickname", 0);
        $liveid    = Request::param("liveid", 0);
        $startTime = Request::param("start_time", 0);
        $endTime   = Request::param("end_time", 0);
        $limit     = Request::param("limit", 0);
        $data      = $this->anchorModel(true, $page, $limit, $nickName, $liveid, 0, 0, $startTime, $endTime);
        if (count($data[0])) {
            return json(["code" => 0, "msg" => "", "data" => $data[0], "count" => $data[1]]);
        }

        return self::bulidFail("未查询到相关数据");
    }

    public function export_anchor()
    {
        $nickName  = Request::param("nickname", 0);
        $orderNo   = Request::param("order_no", 0);
        $status    = Request::param("status", 0);
        $startTime = Request::param("start_time", 0);
        $endTime   = Request::param("end_time", 0);
        $limit     = Request::param("limit", 0);
        $data      = $this->anchorModel(false, 0, 0, $nickName, $orderNo, $status, $startTime, $endTime)[0];
        if (empty($data)) {
            return $this->error('未查询到相关数据');
        }

        $writer = WriterEntityFactory::createXLSXWriter();
        $file   = "{$_SERVER['DOCUMENT_ROOT']}/uploads/" . time() . rand(10000, 99999) . 'xlsx';
        $writer->openToFile($file);
        $header    = [
            WriterEntityFactory::createCell('ID'),
            WriterEntityFactory::createCell('订单号'),
            WriterEntityFactory::createCell('用户名'),
            WriterEntityFactory::createCell('订单类型'),
            WriterEntityFactory::createCell('订单金额'),
            WriterEntityFactory::createCell('应付金额'),
            WriterEntityFactory::createCell('购买宝石'),
            WriterEntityFactory::createCell('赠送宝石'),
            WriterEntityFactory::createCell('支付单号'),
            WriterEntityFactory::createCell('支付渠道'),
            WriterEntityFactory::createCell('下单时间'),
            WriterEntityFactory::createCell('支付状态'),
        ];
        $singleRow = WriterEntityFactory::createRow($header);
        $writer->addRow($singleRow);
        foreach ($data as $v) {
            $typeName = '';
            switch ($v['type']) {
                case 0:
                    $typeName = '购买钻石';
                    break;
                case 1:
                    $typeName = '开通贵族';
                    break;
                default:
                    $typeName = '其它';
            }
            $payChannel = '';
            switch ($v['pay_channel']) {
                case 1:
                    $payChannel = '微信';
                    break;
                case 2:
                    $payChannel = '支付宝';
                    break;
                case 3:
                    $payChannel = '苹果支付';
                    break;
                case 4:
                    $payChannel = '其他';
                    break;
                case 5:
                    $payChannel = '人工';
                    break;
                default:
                    $payChannel = '其它';
            }

            $payStatus = '';
            switch ($v['pay_status']) {
                case 0:
                    $payStatus = '等待支付';
                    break;
                case 1:
                    $payStatus = '支付成功';
                    break;
                case 2:
                    $payStatus = '支付取消';
                    break;
                case 3:
                    $payStatus = '支付失败';
                    break;
                default:
                    $payStatus = '其它';
            }
            $cells          = [
                WriterEntityFactory::createCell($v['id']),
                WriterEntityFactory::createCell($v['order_no']),
                WriterEntityFactory::createCell($v['user']['nick_name']),
                WriterEntityFactory::createCell($typeName),
                WriterEntityFactory::createCell($v['pay_amount']),
                WriterEntityFactory::createCell($v['amount']),
                WriterEntityFactory::createCell($v['gold']),
                WriterEntityFactory::createCell($v['gold_added']),
                WriterEntityFactory::createCell($v['out_trade_no']),
                WriterEntityFactory::createCell($payChannel),
                WriterEntityFactory::createCell($v['create_time']),
                WriterEntityFactory::createCell($payStatus),
            ];
            $multipleRows[] = WriterEntityFactory::createRow($cells);
        }

        $writer->addRows($multipleRows);

        $writer->close();
        return download($file, '主播报表.xlsx');
    }

    /**
     * 经纪人报表统计
     */
    function manager()
    {
        $this->timeSet();
        return $this->fetch();
    }

    function get_manager_list()
    {
        $page       = Request::param("page");
        $limit      = Request::param("limit");
        $start_time = Request::param("start_time", 0);
        $end_time   = Request::param("end_time", 0);
        $guild_id   = $this->guild_id;

        $where = [
            "guild_id={$guild_id}",
            "role_id<>2"
        ];
        if ($this->hight_auth != 1) {
            $where[] = "(FIND_IN_SET({$this->manager_id},path_ids) OR id={$this->manager_id})";
        }
        $where = implode(' AND ', $where);

        $list = GuildManagerModel::with(['role', 'parent'])->where($where)->field('password,token', true)
            ->limit(($page - 1) * $limit, $limit)
            ->order("id", "desc")->select();

        if (count($list) > 0) {
            $count = GuildManagerModel::where($where)->count();

            // 根据经纪人查询下级主播人数
            foreach ($list as &$item) {
                $user_ids = $this->getGuildManageUserId($item);
                list($on_live_count, $open_total) = $this->getOpenLiveCount($user_ids, $start_time, $end_time);
                $item->anchor_count = count($user_ids);
                // 正在直播中
                $item->on_live_count = $on_live_count;
                // 开播人数
                $item->open_live_count = $open_total;
            }

            return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    /**
     * 获取开播人数
     */
    private function getOpenLiveCount($user_ids, $start_time = '', $end_time = '')
    {
        // 首先查询正在直播数
        $on_where = [
            ['anchorid', 'in', $user_ids],
            ['status', '=', 1],
        ];
        if ($start_time) {
            $on_where[] = ["start_stamp", ">=", strtotime($start_time)];
        }
        if ($end_time) {
            $on_where[] = ["start_stamp", "<=", strtotime($end_time)];
        }
        $on_live = LiveModel::where($on_where)->column('anchorid');
        $on_live = array_filter(array_unique($on_live));

        // 查询历史直播人数
        $ls_where = [
            ['anchorid', 'in', $user_ids],
        ];
        if ($start_time) {
            $ls_where[] = ["end_stamp", ">=", strtotime($start_time)];
        }
        if ($end_time) {
            $ls_where[] = ["end_stamp", "<=", strtotime($end_time)];
        }
        $live_history = LiveHistoryModel::where($ls_where)->column('anchorid');

        // 开播人数
        $total_open = array_merge($on_live, $live_history);
        $total_open = array_filter(array_unique($total_open));

        return array(count($on_live), count($total_open));
    }


    /**
     * 所属代理的主播id
     */
    private function getGuildManageUserId($manager_info)
    {
        $where = [
            ['guild_id', '=', $manager_info->guild_id],
            ['status', '=', 0]
        ];
        if ($manager_info->role_id > 2) {
            // 查询自己及下级经纪人
            $where_next   = "(FIND_IN_SET({$manager_info->id},path_ids) OR id={$manager_info->id}) AND guild_id={$manager_info->guild_id}";
            $next_manager = GuildManagerModel::where($where_next)->column('id');

            $where[] = ['guild_manager_id', 'in', $next_manager];
        }
        return UserModel::where($where)->column('id');
    }

    private function timeSet()
    {
        $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $endToday   = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;

        $beginYesterday = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
        $endYesterday   = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1;

        $beginThisweek = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1, date('y'));
        $endThisweek   = time();

        $beginThismonth = mktime(0, 0, 0, date('m'), 1, date('Y'));
        $endThismonth   = mktime(23, 59, 59, date('m'), date('t'), date('Y'));


        //现在的时间到第二天凌晨相差的时间戳
        $beginSeven  = (strtotime(date('Y-m-d')) - 7 * 3600 * 24) - time();
        $beginThirty = (strtotime(date('Y-m-d')) - 30 * 3600 * 24) - time();

        $now = time();
        $day = [
            'n' => [
                'start_time' => date('Y-m-d H:i:s', $beginToday),
                'end_time'   => date('Y-m-d H:i:s', $endToday),
            ],
            'y' => [
                'start_time' => date('Y-m-d H:i:s', $beginYesterday),
                'end_time'   => date('Y-m-d H:i:s', $endYesterday),
            ],
            'w' => [
                'start_time' => date('Y-m-d H:i:s', $beginThisweek),
                'end_time'   => date('Y-m-d H:i:s', $endThisweek),
            ],
            'm' => [
                'start_time' => date('Y-m-d H:i:s', $beginThismonth),
                'end_time'   => date('Y-m-d H:i:s', $endThismonth),
            ],
            's' => [
                'start_time' => date('Y-m-d H:i:s', $beginSeven),
                'end_time'   => date('Y-m-d H:i:s', $now),
            ],
            't' => [
                'start_time' => date('Y-m-d H:i:s', $beginToday),
                'end_time'   => date('Y-m-d H:i:s', $now),
            ],
        ];
        $this->assign("day", json_encode($day));
    }

    public function user()
    {
        return $this->fetch();
    }

    public function user_handle()
    {
        $reg_sources = RegSourceModel::where([['guild_id', '=', $this->guild_id]])->select();

        $source_keys = [];
        foreach ($reg_sources as $key => $value) {
            array_push($source_keys, $value['source_key']);
        }

        $where = [];

        $where[] = ['reg_source_id', 'in', $source_keys];

        if ($mobile = Request::param('mobile')) {
            $where[] = ['mobile', '=', $mobile];
        }
        if ($nickname = Request::param('nickname')) {
            $where[] = ['nick_name', '=', $nickname];
        }
        if ($start_time = Request::param('start_time')) {
            $where[] = ['regist_time', '>=', $start_time];
        }
        if ($end_time = Request::param('end_time')) {
            $where[] = ['regist_time', '<=', $end_time];
        }

        $list = [];
        $count = UserModel::where($where)->count();
        $list = UserModel::where($where)->page(Request::param('page', 1), Request::param('limit', 20))->order('id desc')->select();
        if (count($list) > 0) {
            return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }
}
